package common.helper.toolkit;

import java.io.*;
import java.nio.charset.StandardCharsets;

/*
 * http://blog.csdn.net/stormbjm/article/details/19545941
 */
public class FileToolkit {
	public static void main(String[] args) {
		/*
		String str = readStringFromFile("/elastic_admin/_aliases.json");
		System.out.println(str);
		*/
		/*
		String path = getFullPathInResource("/common.dao.gremlin_admin/gremlin_servers.yml");
		System.out.println(path);
		String url =  FileToolkit.class.getResource("/common.dao.gremlin_admin/gremlin_servers.yml").getPath();
		System.out.println(url);
		*/

	}

	public static String getFullPathInResource(String FILE_IN){
		String path =  FileToolkit.class.getResource(FILE_IN).getPath();
		return path;
	}

	public static String readStringFromFile(String FILE_IN)
	{
		String str="";
		try {
			InputStream in= FileToolkit.class.getResourceAsStream(FILE_IN);
			//FileInputStream in=new FileInputStream(file);
			// size  为字串的长度 ，这里一次性读完
			int size=in.available();
			byte[] buffer=new byte[size];
			in.read(buffer);
			in.close();
			str = new String(buffer,"UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return str;
	}

	public static InputStream getInputStreamFromFile(String FILE_IN) {
		InputStream in  = FileToolkit.class.getResourceAsStream(FILE_IN);
		return in;
	}


	/*
	!!! 该方法有可能造成字符串截断
	 */
	public static String readStringFromStream(InputStream original) {
		InputStream in = original;
		String str="";
		try {
			//InputStream in= FileToolkit.class.getResourceAsStream(FILE_IN);
			//FileInputStream in=new FileInputStream(file);
			// size  为字串的长度 ，这里一次性读完
			int size = in.available();
			byte[] buffer = new byte[size];
			in.read(buffer);
			in.close();
			str = new String(buffer,"UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return str;
	}


	/*
	http://stackoverflow.com/questions/16904386/result-coming-back-from-the-server-is-cutting-off-and-throw-not-valid-json-excep
	 */
	public static String readAllStringFromStream(InputStream inputStream){
		// not much point on allocating a huge buffer here
		char[] buffer = new char[4096];
		InputStreamReader reader = new InputStreamReader(inputStream);
		StringWriter writer = new StringWriter();
		String str = null;
		try {
			while (true) {
				int numRead = reader.read(buffer);
				if (numRead < 0) {
					break;
				}
				writer.write(buffer, 0, numRead);
			}
			str = writer.toString();
			inputStream.close();
			reader.close();
			writer.close();
		}
		catch (Exception e){
			e.printStackTrace();
		}

		return str;
	}


	public static InputStream getInputStreamFromString(String JSON){
		InputStream stream = new ByteArrayInputStream(JSON.getBytes(StandardCharsets.UTF_8));
		return stream;
	}



}
